var express = require("express");
var path = require("path");
var cookieParser = require("cookie-parser");
var logger = require("morgan");
var cors = require("cors");

var stuRouter = require("./routes/stu");
var usersRouter = require("./routes/users");
require("./database/connect.js"); //执行数据库连接

var jwt = require("jsonwebtoken");
var secret = "asdelfka;lsdkjf;alskjdfpla46464asdfasdf"; //签发token时的私钥

var app = express();
app.use(cors()); //解决node服务跨域问题

// node的服务端代理
const { createProxyMiddleware } = require("http-proxy-middleware");
app.use(
  "/smart",
  createProxyMiddleware({
    target: "https://shopapi.smartisan.com",
    changeOrigin: true,
    pathRewrite: { //重写路径，剔除多余的代理路径
      "^/smart": "",
    },
  })
);
app.use(
  "/node",
  createProxyMiddleware({
    target: "http://localhost:3001",
    changeOrigin: true,
    pathRewrite: { //重写路径，剔除多余的代理路径
      "^/node": "",
    },
  })
);


app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());

//静态资源托管
app.use(express.static(path.join(__dirname, "public")));

app.use(
  "/stu",
  (req, res, next) => {
    //中间件拦截函数
    // console.log('在中间件函数中获取headers',req.headers);
    // token合法性    必须本后端签发的token才能验证通过
    // let { token } = req.headers;
    // jwt.verify(token, secret, (err, decoded) => {
    //   console.log(err, decoded);
    //   if (err) {
    //     // 非法token
    //     res.send({
    //       code: 301,
    //       msg: "非法token，请登录",
    //     });
    //     return;
    //   }
    //   // token有效性   必须在指定的时长范围内
    //   let { time, limit } = decoded; //提取token签发时携带的信息
    //   let now = Date.now(); //当前验证token的时间点
    //   if (now - time > limit) {
    //     res.send({
    //       code: 302,
    //       msg: "token已过期，请登录",
    //     });
    //     return;
    //   }
    //   next();
    // });


    // 放行通过 
    next()
  },
  stuRouter
);
app.use("/users", usersRouter);
app.use("/base", require("./routes/index.js"));
app.use("/local", require("./routes/mock.js"));

module.exports = app;
